import axios  from "axios";
import { v4 } from 'uuid';
// interface Respone<T> {
//     code: number;
//     data: T;
// }
// interface ResponeDataList<T> {
//     code: number;
//     data: {
//         total: number;
//         list: T[]
//     };
// }
interface Respone<T> {
    respone: Promise<{code: number, data: T}>,
    cancel: () => void;
}
class ZRequest {
    constructor() {

    }
    protected replaceUrlParam(url: string, param: {[key: string]: any}) {
        for(let key in param) {
            if(typeof param[key] === 'string' || typeof param[key] === 'number') {
                url.replace(`:${key}`, param[key]);
            }
        }
        return url;
    }
    public get<T = any>(url: string, params: {[key: string]: any } = {}, pathParams:{[key: string]: any} =  {}): Respone<T> {
        const _url = this.replaceUrlParam(url, pathParams);
        var source = axios.CancelToken.source();
        let instance = axios.get(_url, {
            cancelToken: source.token,
            headers: {
                token: '123'
            },
            params: params
        }).then(res => {
            return res.data;
        }).catch(() => {
            return {code: -1, data: null}
        });
        return {
            respone: instance,
            cancel: () => {
                source.cancel();
            }
        }
    }
    public getList<T = any>(url: string, param?: {[key: string]: any }, pathParams:{[key: string]: any} =  {}): Respone<{total: number, list: T}> {
        return this.get(url, param, pathParams);
    }
    public post<T = any>(url: string, body: {[key: string]: any }, pathParams:{[key: string]: any} =  {}): Respone<{total: number, list: T}> {
        return this.get(url, body, pathParams);

    }
    public put<T = any>(url: string, param: {[key: string]: any }, pathParam:{[key: string]: any} =  {}): Respone<{total: number, list: T}> {
        return this.get(url, param, pathParam);
    }
    public delete<T = any>(url: string, params: {[key: string]: any } = {}, pathParams:{[key: string]: any} =  {}): Respone<{total: number, list: T}> {
        return this.get(url, params, pathParams);
    }
}

export const Request = new ZRequest();